import React,{useState, useRef, FC} from 'react'
import { Table, Popconfirm, message, Button, Pagination } from 'antd';
import {connect, Dispatch, Loading, UserState, } from 'umi'
import UserModal from './components/UserModal'
import {SingleUserType, FormValues} from './data.d'
import { editRecord, addRecord } from './service';
import { ProColumns, ProTable } from '@ant-design/pro-components';

interface UserPageProps{
    users: UserState,
    dispatch: Dispatch,
    userListLoading: boolean,
}

interface ActionType {
    reload: () => void;
    fetch: () => void;
    rest: () => void;
}

const UserListPage: FC<UserPageProps> = ({
    users, 
    dispatch, 
    userListLoading
}) => {
    const [modalOpen,setModalOpen] = useState(false)
    const [confirmLoading,setConfirmLoading] = useState(false)
    const [record,setRecord] = useState<SingleUserType | undefined>(undefined)
    const ref = useRef<ActionType>();

    const columns:ProColumns<SingleUserType>[] = [
        {
          title: 'Id',
          dataIndex: 'id',
          valueType: 'digit',
          key: 'id',
        },
        {
          title: 'Name',
          dataIndex: 'name',
          valueType: 'text',
          key: 'name',
          render: (text:any) => <a>{text}</a>,
        },
        {
          title: 'create_time',
          dataIndex: 'create_time',
          valueType: 'dateTime',
          key: 'create_time',
        },
        {
          title: 'Action',
          key: 'action',
          valueType: 'option',
          render: (text:any, record:SingleUserType) => [
            <a onClick={()=>{editHandler(record)}}>Edit</a>,
            <Popconfirm
                title="Are you sure to delete this task?"
                onConfirm={()=>{deleteHandler(record)}}
                // onCancel={cancel}
                okText="Yes"
                cancelText="No"
            >
            <a href="#">Delete</a>
            </Popconfirm>
          ],
        },
      ];

    const editHandler = (record:SingleUserType)=> {
        setModalOpen(true)
        setRecord(record)
    };

    const onFinish = async (values: FormValues) => {
        setConfirmLoading(true)
        const id = record ? record.id : 0;

        let serviceFun;
        if (id) {
            serviceFun = editRecord;
        } else {
            serviceFun = addRecord;
        }

        const result = await serviceFun({id, values});
        if(result) {
            setModalOpen(false);
            message.success(`${id === 0 ? 'Add' : 'Edit'} success`);
            reloadHandler();
            setConfirmLoading(false)
        } else {
            setModalOpen(true);
            setConfirmLoading(false)
            message.error(`${id === 0 ? 'Add' : 'Edit'} failed`);
        }
    }

    const deleteHandler = (record:SingleUserType) => {
        const id= record.id;
        dispatch({
            type:'users/delete',
            payload:{
                id,
            }
        })
        message.success('Click on Yes');
    };

    const addHandler = () => {
        setModalOpen(true);
        setRecord(undefined)
    };

    const closeHandler = ()=> {
        setModalOpen(false)
    };

    const reloadHandler = ()=> {
        dispatch({
            type: 'users/getRemote',
            payload: {
                page: users.meta.page,
                per_page: users.meta.per_page,
            },
        });
    };
  
    const paginationHandler = (page: number, pageSize?: number)=>{
        dispatch({
            type: 'users/getRemote',
            payload: {
                page,
                per_page: pageSize ? pageSize : users.meta.per_page,
            },
        });
    }

    const pageSizeHandler = (current: number, size:number) => {
        dispatch({
            type: 'users/getRemote',
            payload: {
                page: current,
                per_page: size,
            },
        });
    }
      
  return (
    <div className='list-table'>
        <ProTable
            columns={columns} 
            rowKey='id' 
            dataSource={users.data}
            loading={userListLoading} 
            search={false} 
            pagination={false}
            options={{
                density: true,
                fullScreen: true,
                reload: ()=>{reloadHandler();},  
                setting: true
            }}
            headerTitle="User List"
            toolBarRender={() => [      
                <Button type='primary' onClick={addHandler}>Add</Button>,
                <Button  onClick={reloadHandler}>Reload</Button>,
            ]}
        />
        <Pagination
            total={users.meta.total}
            onChange={paginationHandler}
            onShowSizeChange={pageSizeHandler}
            current={users.meta.page}
            showSizeChanger
            showQuickJumper
            showTotal={(total) => `Total ${total} items`}
        />
        {/* <Table columns={columns} dataSource={users.data} rowKey='id' loading={userListLoading} /> */}
        <UserModal 
            open={modalOpen} 
            closeHandler={closeHandler} 
            record={record} 
            onFinish={onFinish}
            confirmLoading={confirmLoading}
        />
    </div>
  )
}

const mapStateToProps =({ users, loading }:{users:UserState,loading:Loading})=>{
    return {
        users,
        userListLoading: loading.models.users,
    };
};

export default connect(mapStateToProps)(UserListPage);
